#!/bin/sh

# ########################################################################
# This program is part of percona-nagios-checks (http://code.google.com/p/percona-nagios-checks/)
# License: BSD License (see COPYING)
# Authors:
#  Baron Schwartz
# ########################################################################

# Set up constants, etc.
PROGPATH="$(dirname "$0")"
. $PROGPATH/utils.sh

# Get command-line options
for o; do
   case "${o}" in
      -l) shift; USER="${1}"; shift; ;;
      -p) shift; PASS="${1}"; shift; ;;
      -H) shift; HOST="${1}"; shift; ;;
      -w) shift; WARN="${1}"; shift; ;; # ignored; it's a warning if IO thread stopped
      -c) shift; CRIT="${1}"; shift; ;; # ignored; it's critical if SQL thread errored
   esac
done

EXITSTATUS=$STATE_UNKNOWN
NOTE="UNK replication status"

STATUS="$(mysql -h${HOST} -u${USER} -p${PASS} -ss -E -e "SHOW SLAVE STATUS" | awk '$1 ~ /_Running:|Last_Error:/{print substr($0, 1, 100)}')"

if echo "${STATUS}" | grep 'Last_Error: .' >/dev/null 2>&1 ; then
   EXITSTATUS=$STATE_CRITICAL
   STAT="CRIT"
elif echo "${STATUS}" | grep '_Running: No' >/dev/null 2>&1 ; then
   EXITSTATUS=$STATE_WARNING
   STAT="WARN"
else
   EXITSTATUS=$STATE_OK
   STAT="OK"
fi
NOTE="${STAT} replication ${STATUS}"
echo $NOTE
exit $EXITSTATUS
